<template>
  <div class="main">
  <el-row>
    <el-col :span="24">
      <p class="main_text">基础距离设置</p>
    </el-col>
  </el-row>
  <div class="cyr-flex">
    <el-row class="mb20">
      <el-col :span="20" alig="middle">
        <el-button type="primary" @click="handleAddDialog(dialogFormRef)">添加设置</el-button>
        <el-button @click="handleBatchDelete">批量删除</el-button>
        <el-button @click="handleExportExcel">导出明细</el-button>
      </el-col>
      <el-col :span="4">
        <el-input v-model.lazy.trim="searchVal.keyword" clearable placeholder="搜索拖车公司名称" :suffix-icon="Search"
          @change="handleSearch" />
      </el-col>
    </el-row>
    <div class="cyr-flex-box">
      <el-table :data="tableData"  @selection-change="handleSelectionChange" border v-adaptive :show-overflow-tooltip="true">
          <el-table-column type="selection" width="40" />
          <el-table-column label="序号" type="index" width="55" />
          <el-table-column prop="companyName" label="拖车公司" />
          <el-table-column prop="baseFee" label="基础距离(km)" />
          <el-table-column prop="baseDistance" label="起步价(元)(≤基础距离)" />
          <el-table-column prop="extraFee" label="里程费(元/km)(＞基础距离)" />
          <el-table-column prop="createdAt" label="更新时间" :formatter="dateCompute" />
          <el-table-column prop="ifEnable" label="是否启用" width="120">
            <template #default="scope">
              <el-switch v-model="scope.row.ifEnable" :active-value="1" :inactive-value="0" disabled />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
                  @change="handleCurrentChange" />
      </div>
      <!-- ############################################## 分页 ############################################## -->
  </div>
  <el-dialog v-model="dialogVisible" width="640">
    <template #header>
      <div class="dialog-header">
        <el-button :icon="Edit" color="#FFFFF" link>添加设置</el-button>
      </div>
    </template>
    <el-form label-position="top" label-width="auto" ref="dialogFormRef" :model="dialogForm" class="dialog-form">
      <el-form-item label="拖车公司:" prop="node">
        <el-select v-model="dialogForm.node" placeholder="请选择">
          <el-option v-for="item in TrailCompanyList" :key="item.node" :label="item.companyname" :value="item.node" />
        </el-select>
      </el-form-item>
      <el-form-item label="基础距离(km):" prop="baseDistance">
        <el-input-number v-model="dialogForm.baseDistance" :min="0" />
      </el-form-item>
      <el-form-item label="起步价(元)(≤基础距离):" prop="baseFee">
        <el-input-number v-model="dialogForm.baseFee" :min="0" />
      </el-form-item>
      <el-form-item label="里程费(元/km)(＞基础距离):" prop="extraFee">
        <el-input-number v-model="dialogForm.extraFee" :min="0" />
      </el-form-item>

      <el-form-item label="拖车地址:">
        <el-cascader :options="(pcaTextArr as CascaderOption[])" v-model="addressInfo"> </el-cascader>
      </el-form-item>
      <el-form-item label="详细地址:">
        <el-input v-model="addressDetail" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="是否启用:" class="is-enable" prop="ifEnable">
        <el-switch v-model="dialogForm.ifEnable" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleAdd"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Search, Edit } from '@element-plus/icons-vue';
import type { CascaderOption } from 'element-plus/es/components';
import { RequestGetTrailCompany, RequestGetTrailDistance, RequestAddTrailDistance, RequestDeleteTrailDistance } from '@/api/path/index';
import { pcaTextArr } from 'element-china-area-data';
import moment from 'moment';
import { FormInstance } from 'element-plus';
import { formatJson, formatTimeHan } from '@/utils';
import { exportJson2Excel } from '@/utils/excel';

const dialogVisible = ref(false);
const tableData = ref<any>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogFormRef = ref();
const dialogForm = ref({
  id: '',
  node: '',
  baseDistance: 0,
  baseFee: 0,
  extraFee: 0,
  ifEnable: 0,
  address: '',
});
//地址
const addressInfo = ref([]);
const addressDetail = ref('');

const searchVal = ref({
  keyword: '',
  page: currentPage.value,
  rows: pageSize.value,
});
//输入框查询
const handleSearch = () => {
  currentPage.value = 1;
  searchVal.value.page = currentPage.value
  initData(searchVal.value);
};
//添加弹窗
const handleAddDialog = (formEl: FormInstance | undefined) => {
  dialogVisible.value = true;
  if (!formEl) return;
  dialogFormRef.value?.resetFields();
  dialogForm.value = {
    id: '',
    node: '',
    baseDistance: 0,
    baseFee: 0,
    extraFee: 0,
    ifEnable: 0,
    address: '',
  };
  addressInfo.value = [];
  addressDetail.value = '';
};
//添加
const handleAdd = () => {
  if (dialogForm.value.node === '' || addressInfo.value.length === 0 || addressDetail.value === '') {
    ElMessage.error('请选择拖车公司并填写详细地址')
    return
  }
  dialogForm.value.address = addressInfo.value.join(',') + ',' + addressDetail.value;
  RequestAddTrailDistance(dialogForm.value).then((res: any) => {
    if (res.success == true) {
      dialogVisible.value = false;
      ElMessage.success(res.msg);
      initData(searchVal.value);
    }
  });
};
//取消
const handleCancel = () => {
  dialogVisible.value = false;
  initData(searchVal.value);
};
//编辑
const handleEdit = (item: any) => {
  dialogVisible.value = true;
  dialogForm.value = {
    id: item.id,
    node: item.node,
    baseDistance: item.baseDistance,
    baseFee: item.baseFee,
    extraFee: item.extraFee,
    ifEnable: item.ifEnable,
    address: item.address,
  };
  let addressArr = item.address.split(',');
  addressDetail.value = addressArr.pop().toString();
  addressInfo.value = addressArr;
};
//删除
const ids = ref()
const handleDelete = (id: number) => {
  RequestDeleteTrailDistance([id]).then((res: any) => {
    if (res.success == true) {
      ElMessage.success('删除成功');
      initData(searchVal.value);
    }
  }
  )
};
//批量删除
const handleBatchDelete = () => {
  if (ids.value.length === 0) return
  RequestDeleteTrailDistance(ids.value).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      initData(searchVal.value);
    }
  }
  )
};
//导出
const handleExportExcel = () => {
  const tHeader = ['编号', '拖车公司', '基础距离(km)', '起步价(元)(≤基础距离)', '里程费(km/元)(＞基础距离)', '更新时间', '是否启用']
  const filterVal = ['id', 'companyName', 'baseFee', 'baseDistance', 'extraFee', 'createdAt', 'ifEnable']
  const list = tableData.value.map((item: any, index: number) => {
    return {
      ...item,
      id: index,
      ifEnable: item.ifEnable ? '是' : '否'
    }
  })
  const data = formatJson(filterVal, list)
  exportJson2Excel(tHeader, data, `${formatTimeHan(new Date())}基础距离设置`, undefined, undefined,)
};
// 数据列表
function initData(searchValue: any) {
  RequestGetTrailDistance(searchValue).then((res: any) => {
    tableData.value = res.resultObj.list;
    total.value = res.resultObj.count;
  });
}
//表格选择
const handleSelectionChange = (val: any) => {
  ids.value = val.map((item: any) => {
    return item.id
  });
};
// 拖车公司列表
const TrailCompanyList = ref();
function getTrailCompany() {
  RequestGetTrailCompany().then((res: any) => {
    TrailCompanyList.value = res.resultObj;
  });
}
// 数据时间格式化
const dateCompute = (row: any, column: any, cellValue: any, index: number) => {
  return moment(cellValue).format('YYYY-MM-DD');
};
// 分页
const handleCurrentChange = () => {
  searchVal.value.page = currentPage.value;
  initData(searchVal.value);
};
initData(searchVal.value);
getTrailCompany();
</script>

<style scoped lang="scss">
.main{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.container {
  background: #fff;

  .data-table {
    margin-top: 20px;
  }
}

.el-dialog {
  .el-dialog__header .dialog-header {
    .el-button:hover {
      color: #ffffff;
    }

    .el-button:focus {
      color: #ffffff;
    }
  }

  .el-dialog__body {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      .el-form-item {
        width: 260px;

        .el-input-number {
          width: 100%;
        }
      }

      .is-enable {
        display: flex;
        align-items: center;

        :deep(.el-form-item__label) {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
